package com.clock.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.clock.common.core.domain.AjaxResult;
import com.clock.common.core.domain.entity.SysRole;
import com.clock.shop.domain.ShopShop;
import com.clock.shop.mapper.ShopShopMapper;
import com.clock.shop.service.IShopShopService;
import com.clock.system.domain.SysBoss;
import com.clock.system.mapper.SysRoleMapper;
import com.clock.system.mapper.SysUserMapper;
import com.clock.system.service.impl.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.clock.common.constant.CacheConstants;
import com.clock.common.constant.Constants;
import com.clock.common.constant.UserConstants;
import com.clock.common.core.domain.entity.SysUser;
import com.clock.common.core.domain.model.RegisterBody;
import com.clock.common.core.redis.RedisCache;
import com.clock.common.exception.user.CaptchaException;
import com.clock.common.exception.user.CaptchaExpireException;
import com.clock.common.utils.MessageUtils;
import com.clock.common.utils.SecurityUtils;
import com.clock.common.utils.StringUtils;
import com.clock.framework.manager.AsyncManager;
import com.clock.framework.manager.factory.AsyncFactory;
import com.clock.system.service.ISysConfigService;
import com.clock.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 注册校验方法
 *
 * @author ruoyi
 */
@RequiredArgsConstructor
@Component
public class SysRegisterService {
    @Autowired
    private ISysUserService userService;

    @Resource
    private SysUserMapper userMapper;
    @Autowired
    private RedisCache redisCache;

    @Resource
    private SysRoleMapper roleMapper;

    @Autowired
    private SysBossServiceImpl bossService;

    @Autowired
    private IShopShopService shopShopService;

    private final EmailCodeServiceImpl emailCodeService;
    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(), email=registerBody.getEmail(), code=registerBody.getCode(), uuid=registerBody.getUuid(), role = registerBody.getRole(),
                phoneNumber=registerBody.getPhoneNumber(),idCard=registerBody.getIdCard(),name=registerBody.getName(),licenseNumber=registerBody.getLicenseNumber();

        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPassword(password);
        // 验证验证码
        emailCodeService.authEmailCode(username,code);
        // boolean captchaEnabled = configService.selectCaptchaEnabled();
        // if (captchaEnabled) {
        //     validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        // }

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        }else if(StringUtils.isEmpty(email)){
            msg= "邮箱不能为空";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (!userService.checkUserNameUnique(sysUser)) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            // 验证验证码
           AjaxResult ajaxResult= emailCodeService.authEmailCode(username,code);
            if(ajaxResult.isSuccess()){
                sysUser.setNickName(username);
                sysUser.setPhonenumber(phoneNumber);
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                sysUser.setAvatar(UserConstants.USER_DEFAULT_AVATAR_PATH);
                sysUser.setEmail(email);
                boolean regFlag = userService.registerUser(sysUser);
                // 用户注册赋予角色
                if (Constants.BOSS_ROLE_NAME.equals(role) || Constants.USER_ROLE_NAME.equals(role)) {
                    Long userId = userService.selectUserByUserName(username).getUserId();
                    // LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<>();
                    // query.eq(SysRole::getRoleName, role);
                    Long roleId = roleMapper.selectRoleByRoleName(role).getRoleId();
                    Long[] roleIds = {roleId};
                    // 更新用户角色表
                    userService.insertUserAuth(userId, roleIds);

                    // userServiceImpl.insertUserRole(userId,roleIds);

                    if (Constants.BOSS_ROLE_NAME.equals(role)) {
                        int shopCount= shopShopService.countShopShopByBossId(userId);

                        SysBoss sysBoss = new SysBoss();
                        sysBoss.setBossId(userId);
                        sysBoss.setName(username);
                        sysBoss.setIdCard(idCard);
                        sysBoss.setLicenseNumber(licenseNumber);
                        sysBoss.setOwnShop(shopCount);
                        bossService.insertSysBoss(sysBoss);
                    }
                } else {
                    msg = "请选择适合您的身份再注册哦";
                }
                if (!regFlag) {
                    msg = "注册失败,请联系系统管理人员";
                } else {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                }
            }else {
                msg = ajaxResult.toString() ;
            }

        }
        return msg;
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }

    /**
     * 用户注册发送邮箱验证码
     * @param username 用户名
     * @param email 邮箱
     * @return 操作结果
     */
    public AjaxResult sendEmailCode(String username, String email) {
        // 验证邮箱是否绑定其他用户
        LambdaQueryWrapper<SysUser> qw=new LambdaQueryWrapper<>();
        qw.eq(SysUser::getEmail,email);
        if(userMapper.selectOne(qw)!=null){
            return AjaxResult.error( "注册邮箱已绑定其他账号");
        }else{
            // 发送邮箱验证码
            return emailCodeService.sendEmailCode(username, email);
        }
    }
}
